package com.chf.items;

import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.ai.attributes.AttributeInstance;
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import org.jetbrains.annotations.NotNull;

import java.util.UUID;

/**
 * 红色宝剑物品
 *
 * @author niooooo
 */
public class RedStoneSwordItem extends Item {

    private static final UUID HEALTH_BOOST_UUID = UUID.fromString("a1b2c3d4-5e6f-7a8b-9c0d-ef1234567890");

    public RedStoneSwordItem(Properties properties) {
        super(properties);
    }

    /**
     * 玩家右键点击时触发
     *
     * @param level  {@link Level} 世界
     * @param player {@link Player} 玩家
     * @param hand   {@link InteractionHand} 交互手
     * @return {@link InteractionResultHolder}
     */
    @Override
    public @NotNull InteractionResultHolder<ItemStack> use(@NotNull Level level,
                                                           @NotNull Player player,
                                                           @NotNull InteractionHand hand) {
        ItemStack stack = player.getItemInHand(hand);
        boolean isCreative = player.getAbilities().instabuild;

        // 仅在服务端执行逻辑
        //if (!level.isClientSide()) {
        // TODO 目前学习 暂不判断是否在客户端
        if (true) {
            // 生存模式模式进行以下判断
            if (!isCreative) {
                // 1、冷却检查（true 表示短暂显示在屏幕上方；false 表示保留在聊天框中）
                if (player.getCooldowns().isOnCooldown(this)) {
                    player.displayClientMessage(Component.literal("§c能力冷却中！"), true);
                    return InteractionResultHolder.fail(stack);
                }

                // 2、耐久检查（true 表示短暂显示在屏幕上方；false 表示保留在聊天框中）
                if (stack.getDamageValue() >= stack.getMaxDamage() - 1) {
                    player.displayClientMessage(Component.literal("§c宝剑能量耗尽！"), true);
                    return InteractionResultHolder.fail(stack);
                }

                // 3、应用效果
                this.applyHealthBoost(player, 400);

                // 4、消耗耐久 (10%)
                stack.hurtAndBreak(
                        (int) (stack.getMaxDamage() * 0.1),
                        player,
                        (entity) -> entity.broadcastBreakEvent(hand)
                );
            }

            // 5、设置冷却 (10秒 = 200 ticks)
            player.getCooldowns().addCooldown(this, 200);

            // 6、反馈消息
            player.displayClientMessage(Component.literal("§a生命力量涌动！"), true);

            // 7、播放音效（播放声音实体为空、玩家坐标位置播放音效、播放声音事件、声音类别/来源、声音音量、声音音调）
            level.playSound(null, player.getX(), player.getY(), player.getZ(),
                    SoundEvents.BEACON_ACTIVATE, SoundSource.PLAYERS, 1.0F, 1.2F);
        }

        // 客户端播放动画
        player.swing(hand);
        return InteractionResultHolder.sidedSuccess(stack, level.isClientSide());
    }

    /**
     * 应用最大生命值提升效果
     *
     * @param player        玩家
     * @param durationTicks 持续时间 (ticks)
     */
    private void applyHealthBoost(Player player, int durationTicks) {
        AttributeInstance maxHealth = player.getAttribute(Attributes.MAX_HEALTH);
        if (maxHealth == null) return;

        // 1、创建属性修饰符
        AttributeModifier healthModifier = new AttributeModifier(
                HEALTH_BOOST_UUID,
                // 描述性名称
                "red_stone_sword_health_boost",
                20.0,
                AttributeModifier.Operation.ADDITION
        );

        // 2、移除旧修饰符并添加新修饰符
        maxHealth.removeModifier(HEALTH_BOOST_UUID);
        maxHealth.addTransientModifier(healthModifier);

        // 3、添加标记效果
        player.addEffect(new MobEffectInstance(
                MobEffects.HEALTH_BOOST,
                durationTicks,
                0,
                // 环境效果
                false,
                // 显示粒子
                true,
                // 显示图标
                true
        ));

        // 4、恢复生命值
        if (player.getHealth() < player.getMaxHealth()) {
            player.setHealth(player.getMaxHealth());
        }
    }

    @Override
    public boolean canPerformAction(ItemStack stack, net.minecraftforge.common.ToolAction toolAction) {
        return net.minecraftforge.common.ToolActions.DEFAULT_SWORD_ACTIONS.contains(toolAction);
    }
}
